import log4js from "log4js";
import path from "path";
import { getAppDataPath } from "../utils/app.util";
import { isDev } from "../utils/cmm.util";

/**
 * 日志路径
 */
const logPath = path.resolve(getAppDataPath(), "logs");

/**
 * 日志配置
 */
log4js.configure({
  appenders: {
    stdout: {
      type: "stdout",
      level: "info",
      layout: {
        type: "colored",
      },
    },
    fileInfo: {
      type: "file",
      filename: path.resolve(logPath, "info.log"),
      pattern: "yyyy-MM-dd",
      alwaysIncludePattern: true,
      daysToKeep: 7,
      encoding: "utf-8",
      maxLogSize: 10485760,
      numBackups: 10,
    },
    fileErr: {
      type: "file",
      filename: path.resolve(logPath, "error.log"),
      pattern: "yyyy-MM-dd",
      alwaysIncludePattern: true,
      daysToKeep: 14,
      encoding: "utf-8",
      maxLogSize: 10485760,
      numBackups: 10,
    },
    errorFilter: {
      type: "logLevelFilter",
      appender: "fileErr",
      level: "error",
    },
    debugFilter: {
      type: "logLevelFilter",
      appender: "fileInfo",
      level: "debug",
      maxLevel: "info",
    },
  },
  categories: {
    // 类别
    default: { appenders: ["fileErr"], level: "error" },
    dev: { appenders: ["stdout", "errorFilter", "debugFilter"], level: "debug" },
    prod: { appenders: ["errorFilter", "debugFilter"], level: "info" },
    stdout: { appenders: ["stdout", "errorFilter", "debugFilter"], level: "info" },
  },
});

/**
 * 全局日志实例
 */
export const logger = log4js.getLogger(isDev() ? "stdout" : "stdout");
/**
 * 输出到控制台的日志实例
 * 一般在命令行中使用
 */
export const loggerStdout = log4js.getLogger("stdout");
